<template>
    <el-form :model="modelData"
             :rules="rules"
             ref="form"
             label-width="100px">
      <el-form-item label="名称" prop="name">
        <el-input v-model="modelData.name" placeholder="请输入资源名称"></el-input>
      </el-form-item>
        <el-form-item label="编码" prop="code">
          <el-input v-model="modelData.code" placeholder="请输入资源编码"></el-input>
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <el-select v-model="modelData.icon"
                     placeholder="请输入资源图标">
            <el-option
              v-for="item in iconOptions"
              allow-create
              :key="item"
              :value="item">
              <i :class="'fa ' + item"> </i>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item }}</span>
            </el-option>
          </el-select>
        </el-form-item>
      <el-form-item label="权限" prop="permission">
        <el-select v-model="modelData.permission"
                   filterable
                   allow-create
                   placeholder="输入或请选择"
        @change="handlePermissionSelect">
          <el-option
            v-for="item in urlOptions"
            :key="item.url"
            :label="item.permission"
            :value="item.permission">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="资源类型" prop="type">
        <el-radio-group v-model="modelData.type">
          <el-radio :label="1">菜单</el-radio>
          <el-radio :label="2">按钮</el-radio>
          <el-radio :label="3">URI</el-radio>
        </el-radio-group>
      </el-form-item>

        <el-form-item label="资源路径" prop="url">
          <el-select v-model="modelData.url"
                     filterable
                     allow-create
                     placeholder="输入或请选择">
            <el-option
              v-for="item in urlOptions"
              :key="item.url"
              :label="item.url"
              :value="item.url">
            </el-option>
          </el-select>
        </el-form-item>

      <el-form-item label="上级菜单" prop="uri">
        <el-tree
          ref="tree"
          :data="dataTree"
          node-key="id"
          show-checkbox
          check-strictly
          @check-change="handleCheckChange">
        </el-tree>
      </el-form-item>

      <el-form-item >
          <el-button @click="handleCancel">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </el-form-item>
      </el-form>
</template>

<script>

import { fetchTree, addObj, putObj, getUrl } from 'api/admin/menu'
export default {
  name: 'element',
  data () {
    return {
      methodOptions: ['GET', 'POST', 'PUT', 'DELETE'],
      typeOptions: [
        { name: '菜单', type: 1 },
        { name: '按钮', type: 2 },
        { name: 'URI', type: 3 }
      ],
      iconOptions: [
        'fa-user', 'fa-bell', 'fa-tasks', 'fa-eye', 'fa-cloud', 'fa-group', 'fa-line-chart'
      ],
      modelData: {
        id: 0,
        parentId: 0,
        name: undefined,
        code: undefined,
        icon: undefined,
        description: undefined,
        type: 1,
        permission: undefined,
        url: undefined
      },
      rules: {
        type: [
          { required: true, message: '请输入资源类型', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入资源名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        permission: [
          { required: true, message: '请输入资源权限', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ]
      },
      menuId: -1,
      textMap: {
        update: '编辑',
        create: '创建'
      },
      props: {
        label: 'text',
        children: 'children'
      },
      dataTree: [],
      urlList: undefined,
      urlOptions: undefined,
      timeout: null
    }
  },
  created () {
    fetchTree().then(response => {
      this.dataTree = response.data
    })
    this.doGetUrl()
  },
  mounted () {
  },
  methods: {
    setModel (data) {
      if (!data) {
        this.modelData.id = 0
        // this.$refs.form.resetFields()
      } else {
        this.modelData.id = data.id
        this.modelData.parentId = data.parentId
        this.modelData.code = data.code
        this.modelData.name = data.name
        this.modelData.description = data.description
        this.modelData.icon = data.icon
        this.modelData.type = data.type
        this.modelData.permission = data.permission
        this.modelData.url = data.url
      }
    },
    handleCheckChange (item, checked) {
      if (checked) {
        this.$refs.tree.setCheckedNodes([{
          id: item.id,
          text: item.text
        }])
        this.modelData.parentId = item.id
      } else {
        this.modelData.parentId = 0
      }
    },
    handleSubmit () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.modelData.id < 1) {
            this.add()
          } else {
            this.update()
          }
        }
      })
    },
    handleCancel () {
      this.$emit('cancel')
    },
    update () {
      putObj(this.modelData.id, this.modelData).then(response => {
        let code = parseInt(response.code)
        if (code === 0) {
          this.complete()
        }
      })
    },
    add () {
      addObj(this.modelData).then(response => {
        let code = parseInt(response.code)
        if (code === 0) {
          this.complete()
        }
      })
    },
    handlePermissionSelect (item) {
      console.log(item)
      let select = this.urlOptions.filter((option) => {
        return option.permission === item
      })
      this.modelData.url = select[0].url
    },
    onPermissionSearch (queryString, cb) {
      // 根据用户的输入，选择url
      var options = this.urlList
      console.log(options)
      var results = queryString ? options.filter(this.permissionFilter(queryString)) : options
      clearTimeout(this.timeout)
      this.timeout = setTimeout(() => {
        cb(results)
      }, 3000 * Math.random())
    },
    permissionFilter (queryString) {
      return (state) => {
        return (state.permission.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    doGetUrl () {
      getUrl().then(response => {
        let code = parseInt(response.code)
        if (code === 0) {
          this.urlList = response.data
          this.urlOptions = this.urlList.filter((item) => {
            return item.permission.length > 0
          })
          console.log(this.urlOptions)
        }
      })
    },
    complete () {
      this.$refs.tree.setCheckedNodes([])
      this.$refs.form.resetFields()
      this.$emit('complete')
    }
  }
}
</script>
